import {
  collectArticleAPI,
  disCollectArticleAPI,
  followAPI,
  disfollowAPI,
} from './../../api/article';
import store, { AppDispatch } from '@/store';
import {
  disLikeArticleAPI,
  getArticleByIdAPI,
  getArticleDetailByIdAPI,
  likeArticleAPI,
} from '@/api/article';
import { ActionType } from '../reducer/article';
import { Toast } from 'antd-mobile';

export const getArticleByIdAction = (channel_id: number, timestamp = Date.now()) => {
  return async (dispatch: AppDispatch) => {
    const res = await getArticleByIdAPI(channel_id, timestamp);
    dispatch({ type: 'article/saveArticle', payload: { channel_id, data: res.data } });
  };
};

export const refreshArticleAction = (channel_id: number) => {
  return async (dispatch: AppDispatch) => {
    const res = await getArticleByIdAPI(channel_id);
    dispatch({ type: 'article/refresh', payload: { channel_id, data: res.data } });
  };
};

export const getArticleDetailAction = (art_id: string) => {
  return async (dispatch: AppDispatch) => {
    const res = await getArticleDetailByIdAPI(art_id);
    dispatch({ type: 'article/saveDetail', payload: res.data });
  };
};

export const clearDetailAction = (): ActionType => ({
  type: 'article/saveDetail',
  payload: {} as any,
});

export const likeArticleAction = (id: string, hasLike: boolean) => {
  return async (dispatch: AppDispatch) => {
    if (hasLike) {
      await disLikeArticleAPI(id);
    } else {
      await likeArticleAPI(id);
    }
  };
};

export const collectArticleAction = () => {
  return async (dispatch: any, getState: typeof store.getState) => {
    const { detail } = getState().article;
    const { art_id } = detail;
    const hasCollect = detail.is_collected;

    if (hasCollect) {
      await disCollectArticleAPI(art_id);
    } else {
      await collectArticleAPI(art_id);
    }

    dispatch(getArticleDetailAction(detail!.art_id));
    Toast.show({ content: hasCollect ? '取消收藏' : '收藏文章' });
  };
};

// 2.
export const followAction = () => {
  return async (dispatch: any, getState: typeof store.getState) => {
    const { detail } = getState().article;
    if (detail.is_followed) {
      await disfollowAPI(detail.aut_id);
    } else {
      await followAPI(detail.aut_id);
    }
    dispatch(getArticleDetailAction(detail!.art_id));
    Toast.show({ content: detail.is_followed ? '取消成功' : '关注成功' });
  };
};
